package com.sunreal.paygateway.sys.config;

import java.util.Collection;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.sunreal.paygateway.sys.dao.model.SysUser;
import com.sunreal.paygateway.sys.service.ShiroService;

/**
 * 功能描述：自定义Realm
 *
 * @Author 彭广
 * @Date 2019/4/15
 */

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private ShiroService shiroService;

//    @Autowired
//    private SessionDAO sessionDAO;

    /***
     * 获取认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) at;
        // 通过表单接收的用户名
        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());
        SysUser user = shiroService.getUserByUsername(username);
        if (user == null) {
            throw new UnknownAccountException(); //如果用户名密码错误
        }
//        UserInfo info = new UserInfo();
//        info.setUserId(user.getUserId());
//        info.setIdCard(user.getIdcard());
//        info.setUserName(user.getUsername());
//        info.setShowName(user.getShowName());
        //以下为只允许同一账户单个登录
//        Collection<Session> sessions = sessionDAO.getActiveSessions();
//        if(sessions.size()>0) {
//            for (Session session : sessions) {
//                //如果和当前session是同一个session，则不剔除
//                if (SecurityUtils.getSubject().getSession().getId().equals(session.getId())){
//                    break;
//                }
//                //获得session中已经登录用户的名字
//                SimplePrincipalCollection coll = (SimplePrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
//                SysUser actUser = (SysUser)coll.getPrimaryPrincipal();
//                if(actUser != null) {
//                    if (username.equals(actUser.getUsername())) {  //这里的username也就是当前登录的username
//                        sessionDAO.delete(session);
//                    }
//                }
//            }
//        }
        return new SimpleAuthenticationInfo(user,token.getPassword(),getName());
    }
    /***
     * 获取授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
        // 根据自己系统规则的需要编写获取授权信息，这里为了快速入门只获取了用户对应角色的资源url信息
        String username = (String) pc.fromRealm(getName()).iterator().next();
        if (username != null) {
            List<String> perm = shiroService.getPermissionsByUsername(username);
            if (perm != null && !perm.isEmpty()) {
                SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
                for (String each : perm) {
                    // 将权限资源添加到用户信息中
                    info.addStringPermission(each);
                }
                return info;
            }
        }
        return null;
    }

}
